<template>
  <div
    :class="['tinymce-editor relative', { fixedHead: fixHead }]"
    :style="{ height: height }"
  >
    <Editor
      :id="id"
      v-model="contentValue"
      :init="init"
      :disabled="disabled"
      @onDblclick="onClick"
    />
    <div class="content-title-box" v-if="showTitle">
      <el-input placeholder="请输入页面标题" v-model="contentTitle"></el-input>
    </div>
    <el-dialog
      title="上传进度"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
    >
      <el-progress
        :text-inside="true"
        :stroke-width="26"
        :percentage="percentage"
      ></el-progress>
    </el-dialog>
    <div
      id="tinymce_vue_wzlbEdit"
      v-html="contentValue"
      style="position: fixed; visibility: hidden"
    ></div>
    <el-dialog
      customClass="tinymce-dialog"
      :close-on-click-modal="false"
      title="查看图片"
      :visible.sync="dialogVisible"
      width="70%"
      :append-to-body="true"
      @close="cancel"
    >
      <img id="big-img" :src="imgUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import Editor from "@tinymce/tinymce-vue";
import "tinymce/tinymce"; //tinymce默认hidden，不引入则不显示编辑器
import "tinymce/themes/silver/theme"; // 引用主题文件
import "tinymce/icons/default"; // 引用图标文件
import "tinymce/plugins/link";
import "tinymce/plugins/code";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/autolink"; //锚点
import "tinymce/plugins/autoresize";
import "tinymce/plugins/autosave";
import "tinymce/plugins/charmap"; //特殊字符
import "tinymce/plugins/code"; //查看源码
import "tinymce/plugins/codesample"; //插入代码
import "tinymce/plugins/directionality"; //
import "tinymce/plugins/fullpage"; //页面属性编辑
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/help"; //帮助
import "tinymce/plugins/hr"; //横线
import "tinymce/plugins/image"; //图片
import "tinymce/plugins/imagetools"; //图片工具
import "tinymce/plugins/importcss"; //图片工具
import "tinymce/plugins/insertdatetime"; //时间插入
import "tinymce/plugins/media"; //媒体插入
import "tinymce/plugins/nonbreaking"; //
import "tinymce/plugins/noneditable"; //不间断空格
import "tinymce/plugins/pagebreak"; //分页
import "tinymce/plugins/paste"; //粘贴
import "tinymce/plugins/preview"; //预览
import "tinymce/plugins/print"; //打印
import "tinymce/plugins/quickbars"; //快捷菜单
import "tinymce/plugins/save"; //保存
import "tinymce/plugins/searchreplace"; //查询替换
import "tinymce/plugins/spellchecker"; //拼写检查
import "tinymce/plugins/tabfocus"; //
import "tinymce/plugins/template"; //插入模板
import "tinymce/plugins/textpattern"; //
import "tinymce/plugins/toc"; //
import "tinymce/plugins/visualblocks"; //
import "tinymce/plugins/visualchars"; //
import "tinymce/plugins/wordcount"; //数字统计
import {
  deleteUrls,
  get_urlImgVideo,
  arrayDifference,
} from "@/utils/tinymce.js";

export default {
  components: {
    Editor,
  },
  props: {
    id: {
      type: String,
      default: "basic-example",
    },
    height: { type: String, default: "100%" },
    fixHead: {
      type: Boolean,
      default: true,
    },
    showTitle: {
      type: Boolean,
      default: true,
    },
    fixedHead: {
      type: Boolean,
      default: true,
    },
    pageContent: {
      type: String,
      default: "",
    },
    pageTitle: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    showMessage: {
      type: Boolean,
      default: true,
    },
    plugins: {
      type: [String, Array],
      default:
        "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave ",
    },
    toolbar: {
      type: [String, Array],
      default:
        // 'formatselect | fontsizeselect | fontselect | bold italic underline forecolor backcolor subscript superscript |\
        //  numlist bullist | outdent indent aligncenter alignleft alignright alignjustify lineheight |\
        //  image media link preview table |\
        //  formats undo redo'
        "formatselect  fontsizeselect  fontselect  bold italic underline forecolor backcolor subscript superscript \
         numlist bullist | outdent indent aligncenter alignleft alignright alignjustify lineheight \
         image media link preview table \
         formats undo redo",
    },
  },
  data() {
    return {
      imgUrl: "",
      dialogVisible: false,
      contentValue: this.pageContent,
      contentTitle: this.pageTitle,
      urlImgVideo_start: [], //页面一加载完，就获取编辑器内容中的img和video地址
      urlImgVideo_uploaded: [], //所有上传的img和video的地址。包括 原来已上传的+新上传的地址
      urlImgVideo_end: [], //最后提交编辑内容时，当前的编辑器内容中的img和video地址
      deleteUrlsList: [], // 要删除的图片
      percentage: 0,
      dialogTableVisible: false, //上传进度窗口
      init: {
        language_url: "/static/tinymce/langs/zh_CN.js", //引入语言包文件
        language: "zh_CN", //语言类型
        skin_url: "/static/tinymce/skins/ui/oxide", //皮肤：浅色
        content_css: "/static/tinymce/mycontent.css",
        menubar: false, // 隐藏菜单栏
        autoresize_bottom_margin: 50,
        // min_height: 600,
        branding: false,
        elementpath: false,
        resize: false, // 禁止改变大小
        statusbar: false, // 隐藏底部状态栏
        paste_data_images: true, // 是否允许粘贴图片
        contextmenu: false, // 禁用富文本的右键菜单，使用浏览器自带的右键菜单
        toolbar_mode: "none",
        plugins:
          "wordcount visualchars visualblocks textpattern template tabfocus searchreplace save print preview paste pagebreak noneditable nonbreaking media insertdatetime importcss image media hr help fullscreen directionality codesample code charmap link code table lists advlist anchor autolink autoresize autosave", // 插件需要import进来
        toolbar: this.toolbar,
        content_style: "p {margin: 5px 0; font-size: 14px;color:#222f3e;}",
        fontsize_formats:
          "2pt 4pt 6pt 8pt 12pt 14pt 16pt 18pt 24pt 36pt 48pt 56pt 72pt",
        font_formats:
          "仿宋_GB2312=FangSong_GB2312;宋体=simsun,serif;仿宋体=FangSong,serif;楷体_GB2312=KT2312;楷体=KaiTi;微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;黑体=SimHei,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
        file_picker_types: "file image media", //添加后才会显示出本地上传图标
        //   图片上传
        images_upload_handler: (blobInfo, success) => {
          let _this = this;
          _this.upload(blobInfo.blob(), (e) => {
            success(e);
          });
        },
        //上传文件
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype === "media" || meta.filetype === "file") {
            let input = document.createElement("input"); //创建一个隐藏的input
            input.setAttribute("type", "file");
            let _this = this;
            input.onchange = function () {
              let file = this.files[0]; //选取第一个文件
              console.log(file);
              _this.upload(file, (e) => {
                if (meta.filetype === "media") {
                  callback(e);
                } else {
                  callback(e, { title: file.name, text: file.name });
                }
              });
            };
            //触发点击
            input.click();
          }
        },
      },
    };
  },
  watch: {
    pageContent: {
      handler(newValue) {
        console.log("pageContent");
        this.contentValue = newValue;
        this.$nextTick(() => {
          this.urlImgVideo_start = [...get_urlImgVideo("tinymce_vue_wzlbEdit")];
          this.urlImgVideo_uploaded = [...this.urlImgVideo_start];
        });
      },
      immediate: true,
    },
    contentValue(newValue) {
      this.$emit("contentEmit", newValue);
      // this.$nextTick(() => {
      //   this.urlImgVideo_uploaded = [
      //     ...get_urlImgVideo("tinymce_vue_wzlbEdit"),
      //   ];
      // });
    },
    pageTitle(newValue) {
      this.contentTitle = newValue;
    },
    contentTitle(newValue) {
      this.$emit("changeTitle", newValue);
    },
  },
  created() {},
  mounted() {},
  methods: {
    onClick(e) {
      if (e.target.localName === "img") {
        let imgUrl = e.target.currentSrc;
        this.imgUrl = imgUrl;
        this.dialogVisible = true;
        console.log("imgUrl", e, imgUrl);
      }
    },
    cancel() {
      this.imgUrl = "";
      this.dialogVisible = false;
    },
    changeContent() {
      console.log("changeContent", this.contentValue);
      this.getDelList();
      this.$emit("contentEmit", this.contentValue);
    },
    deleteEditorList() {
      if (!this.deleteUrlsList || this.deleteUrlsList.length === 0) {
        return false;
      }
      console.log("删除接口", this.deleteUrlsList);
      this.dele(this.deleteUrlsList);
    },
    getDelList() {
      this.deleteUrlsList = [];
      //删除已上传到服务器中的那些在编辑器内容中没有使用的img和video地址
      this.urlImgVideo_end = [...get_urlImgVideo("tinymce_vue_wzlbEdit")];
      if (this.urlImgVideo_uploaded.length !== 0) {
        this.deleteUrlsList = deleteUrls(
          arrayDifference(this.urlImgVideo_uploaded, this.urlImgVideo_end)
        );
      }
    },
    //清空内容
    clear() {
      this.contentValue = "";
    },
    // 上传
    upload(file, fn) {
      console.log(
        "%c [ file, fn ]-283",
        "font-size:13px; background:pink; color:#bf2c9f;",
        file,
        fn
      );
      const formData = new FormData();
      formData.append("pathType", "files");
      formData.append("file", file);
      // uploadFile(formData)
      //   .then(res => {
      //     if (res.code === 200) {
      //       if (this.showMessage) {
      //         this.$message.success(res.message)
      //       }
      //       let file = res.data
      //       this.urlImgVideo_uploaded.push(file.servicePath)
      //       fn && fn(file.servicePath)
      //     } else {
      //       this.$message.error('上传失败!')
      //       fn && fn('')
      //     }
      //   })
      //   .catch(() => {
      //     this.$message.error('上传失败!')
      //     fn && fn('')
      //   })
    },
    // 删除
    dele(list) {
      let params = {
        files: list,
      };
      console.log(
        "%c [ params ]-309",
        "font-size:13px; background:pink; color:#bf2c9f;",
        params
      );
      // deleteFile(params).then(() => {})
    },
  },
};
</script>
<style>
#big-img {
  width: 100%;
  object-fit: fill;
  display: inline-block;
}
.content-title-box {
  display: inline-block;
  position: absolute;
  top: 75px;
  padding: 20px;
  width: 100%;
  margin: 0;
  outline: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background: none;
  border: none;
  box-shadow: none;
}
.content-title-box .el-input__inner {
  border-color: transparent;
  height: 46px;
  line-height: 46px;
  font-size: 28px;
}
.tinymce-editor {
  width: 100%;
  background: #fff;
  height: 100%;
}
.tox .tox-sidebar-wrap {
  overflow: auto;
}
.tinymce-editor .tox-editor-header {
  z-index: 9;
  background: #fff;
  width: 100%;
  border-bottom: 1px solid #dfe1e5;
}
.tinymce-editor.fixedHead .tox-editor-header {
  position: fixed;
}
.tinymce-editor .tox-sidebar-wrap {
  /* padding-top: 120px; */
}
.fixedHead.tinymce-editor .tox-sidebar-wrap {
  padding-top: 130px;
}

.tinymce-editor.fixedHead .tox-tinymce {
  border: none;
  min-height: 200px;
  height: 100% !important;
}
/* .tinymce-editor .tox-tinymce {
  height: 100% !important;
} */
.tinymce-editor #tinymce {
  overflow-y: auto !important;
  overflow: auto !important;
}
.tinymce-editor .tox .tox-tbtn {
  /* width: 40px;
  height: 40px; */
  margin: 0;
}
.tinymce-editor .tox .tox-tbtn--select {
  width: auto;
  height: 40px;
}
.tox .tox-toolbar {
  display: block !important;
}
.tinymce-editor .tox .tox-toolbar__group {
  height: 100%;
  font-size: 12px;
  border: none;
  border-bottom: 1px solid #dfe1e5;
}
.tox .tox-toolbar,
.tox .tox-toolbar__overflow,
.tox .tox-toolbar__primary {
  background: none !important;
  margin-bottom: none !important;
  border-bottom: 1px solid #ccc;
}
.tinymce-editor .tox .tox-tbtn--bespoke .tox-tbtn__select-label {
  /* width: 4rem; */
  width: auto;
}
.tinymce-editor .tox-icon.tox-tbtn__icon-wrap svg {
  fill: #222f3e;
}
.tinymce-editor .tox .tox-toolbar {
  /* padding-top: 6px; */
}
.tinymce-editor .tox .tox-toolbar,
.tox .tox-toolbar__overflow,
.tox .tox-toolbar__primary {
  border-top: none;
}
.tinymce-editor .tox .tox-tbtn--enabled {
  background: #ccc;
  color: #222f3e;
}
.tinymce-editor .tox .tox-tbtn--enabled svg {
  fill: #222f3e;
}
.tinymce-editor .tox .tox-tbtn--enabled:hover {
  background: #ccc;
}
.tinymce-editor .tox .tox-tbtn--enabled:hover svg {
  fill: #222f3e;
}
.tinymce-editor .tox .tox-toolbar__group:not(:last-of-type) {
  border-color: #dfe1e5;
  border-right: none !important;
}
.tinymce-editor .tox .tox-edit-area {
  border-top: none;
}
.tox.tox-silver-sink.tox-tinymce-aux {
  z-index: 3002;
}
</style>
